﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using imaginecup.util;

namespace Imaginecup.util.collision
{
    public class Collision
    {

        public static bool ContainPoint(Vector2 pos, Vector2 size, Vector2 point)
        {
            if ((pos.X < point.X && pos.X + size.X > point.X) &&
                (pos.Y < point.Y && pos.Y + size.Y > point.Y))
            {
                return true;
            }
            return false;
        }

        public static bool CollisionByRect(Vector2 pos, Vector2 size, Vector2 pos2, Vector2 size2)
        {
            if ((pos.X < pos2.X + size2.X && pos.X + size.X > pos2.X) &&
                (pos.Y < pos2.Y + size2.Y && pos.Y + size.Y > pos2.Y))
                return true;

            return false;
        }

        public static bool CollisionByRect(Vector2 pos, Vector2 size, Vector2 pos2, float size2X, float size2Y)
        {
            if ((pos.X < pos2.X + size2X && pos.X + size.X > pos2.X) &&
                (pos.Y < pos2.Y + size2Y && pos.Y + size.Y > pos2.Y))
                return true;

            return false;
        }

        public static bool CollisionLineWithRect(Vector2 lineStart, Vector2 lineEnd , Vector2 pos , Vector2 size)
        {
            float lineLength = Vector2.Distance(lineStart, lineEnd);
            Vector2 dir = Vector2.Subtract(lineEnd, lineStart);
            dir.Normalize();

            Vector2 rightBottom = new Vector2(pos.X + size.X , pos.Y + size.Y);
            BoundingBox box = new BoundingBox(new Vector3(pos, 0.0f), new Vector3(rightBottom, 0.0f));
            Ray ray = new Ray(new Vector3(lineStart, 0.0f), new Vector3(dir, 0.0f));

            // 충돌 결과는 거리로, 충돌이 되지 않으면 null이 리턴된다.
            float? result = box.Intersects(ray);

          
            // 충돌거리가 직선의 길이보다 작으면 충돌로 처리한다.
            if (result != null && result <= lineLength)
                return true;

            return false;
        }


        public static bool CollisionByPoint(EntityInfo entity , Vector2 pos)
        {
            return ContainPoint(entity.mPosition, entity.mSize, pos);
        }

        public static bool CollisionByRect(EntityInfo entity1 , EntityInfo entity2)
        {
            return CollisionByRect(entity1.mPosition, entity1.mSize, entity2.mPosition, entity2.mSize);
        }
      
    }
}
